--
-- @Author:      qinxugao
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的派发

local skynet = require "skynet"
local log = require "Log"
local md5 = require "md5"
local crypt = require "crypt"
local cjson = require "cjson"

local msgpack = require "msgpack_helper"
local AssertEx = AssertEx
local Message = class("Message")


function Message:ctor()
	self.tbSelfMsg = {} --本服务要监听的消息
	self.tbOtherMsg = {} --别服务要监听的消息
	self.tbNodeMsg = {} --别节点(进程)要监听的消息
end

--注册本服务里的消息
function Message:registerSelf(msgName,callback)
	self.tbSelfMsg[msgName] = callback
end

function Message:registerNode(msgName,nodeName,serviceName,userProperty)
	self.tbNodeMsg[msgName] = self.tbNodeMsg[nodeName] or {}
	self.tbNodeMsg[msgName]["nodeName"] = nodeName 
	self.tbNodeMsg[msgName]["serviceName"] = serviceName
	self.tbNodeMsg[msgName]["userProperty"] = userProperty --需要转递的用户属性
end

function Message:registerOther(msgName,svrName)
	self.tbOtherMsg[msgName] = self.tbOtherMsg[msgName] or {}
	self.tbOtherMsg[msgName]["svrName"] = svrName 
	
end

--客户端消息派发
function Message:dispatchMessage(fd, cmd, args)
	
	local ok, res
	local func = self.tbSelfMsg[cmd] -- gate是否有handler

	if not func then --没有，则转发出去
		--ok, r = router_helper.router_msg(u_info.user, cmd, args)
		ok = true
		local svr = self.tbOtherMsg[cmd]
		if svr then
			res = skynet.call(svr,'lua', cmd, args)
		else
			log.error('#########__Message_globalsvr_request cmd no found:'..cmd)
			--res = "unknown client request:"..cmd
		end				
	else--有，则调用本服务上的handler
		ok, res = x_pcall(func, args)
	end

	if not ok then
		if type(res) == "table" and res.err then
			res.err = nil
			log.error(tostring(res))
		else
			log.error(tostring(res))
			res = { error_res = { err_no = -1, err_msg = "internal error" }}
		end
	else
		if res then 
			if type(res) == "table" and res.err then
				res.err = nil --因为proto 中没有err字段所有这里把他设置为空
			end
			--log.debug(res) 
		end
	end
	--返回的消息发给客户端
	if res then
		if type(res) == 'table' then
			for k,v in pairs(res) do
				if not msgpack.send_json_message(fd, "socket", k, v) then
					log.error('##########send_message to web faild on handle cmd:',cmd)
				end
			end
		end
	end
end

--取dispatchMessage函数地址
function Message:dispatch()
	return handler(self,self.dispatchMessage)
end

--lua消息
function Message:dispatchSelf(session, source, cmd, ... )
	local func = self.tbSelfMsg[cmd] -- gate是否有handler
	-- print(session, source, cmd,"____________dispatchSelf")
	if not func then 
		log.error("####### cmd "..cmd .." not found at game "..self.svrName)
		return
	end
	if cmd == 'socket' then 
		skynet.retpack(xx_pcall(func, source, ...))
	else
		skynet.retpack(xx_pcall(func, ...))
	end
end

function Message:dispatchSelfHandle()
	return handler(self,self.dispatchSelf)
end
return Message